

import { Injectable } from '@angular/core';
import { leaveView } from '@angular/core/src/render3/state';
import { ApiService } from './api.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { LeaveRequest } from '../domain/leave-request';
/*

@Author:赵明洋

@Date: 2018-12-12

@员工请假服务

@Last Modified time: 2018-12-16
*/
const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
export class LeaveTest {
  user_id: number;
  start_time: string;
  end_time: string;
  reason: string;
  state: number; //审批状态
  duration: number; //请假时长
  type: number; //请假
}

@Injectable({
  providedIn: 'root'
})


export class LeaveRequestStateService {
  private api_url;
  private headers;

  constructor(private apiService: ApiService,
    private http: HttpClient) {
    this.api_url = apiService.getUrl();
    this.headers = apiService.getHeaders();
  }
  //获取请求信息
  getLeaveRequests(): Observable<LeaveRequest[]> {
    return this.http.get<LeaveRequest[]>(this.api_url + "/leave_requests")
      .pipe(
        catchError(this.handleError('getLeaveRequests', []))
      );
  }
  //根据id获取单个请求信息
  getLeaveRequest(id: number): Observable<LeaveRequest[]> {
    return this.http.get<LeaveRequest[]>(this.api_url + "/leave_requests" + "?id=" + id)

  }


  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      console.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }

  /** POST: add a new hero to the database */
  addLeaveRequest(leaveTest: LeaveTest): Observable<any> {
    return this.http.post(this.api_url + "/leave_requests", leaveTest, this.headers)
      .pipe(
        catchError(this.handleError('addLeaveRequest', leaveTest))
      );
  }

  upDateLeaveRequest(leaveRequest: LeaveRequest): Observable<any> {
    return this.http.put(this.api_url + "/leave_requests/" + leaveRequest.id, leaveRequest, this.headers)
      .pipe(
        catchError(this.handleError('upDateLeaveRequest', leaveRequest))
      );
  }


  deleteLeaveRequest(leaveRequest: LeaveRequest): Observable<any> {
    return this.http.delete(this.api_url + "/leave_requests/" + leaveRequest.id)
      .pipe(
        catchError(this.handleError('deleteLeaveRequest', []))
      );
  }

}
